# ik_analyzer.py

import requests


class IKAnalyzer:
    def __init__(self, es_host="http://host.docker.internal:9200"):
        self.es_host = es_host

    def _analyze(self, text, analyzer="ik_smart"):
        url = f"{self.es_host}/_analyze"
        data = {
            "analyzer": analyzer,
            "text": text
        }

        try:
            response = requests.post(url, json=data, headers={'Content-Type': 'application/json'})
            if response.status_code == 200:
                result = response.json()
                tokens = [token['token'] for token in result['tokens']]
                return tokens
            else:
                print(f"[错误] 分析失败: {response.status_code}")
                return []
        except Exception as e:
            print(f"[异常] 请求失败: {e}")
            return []

    def analyze_smart(self, text):
        """智能分词，粗粒度"""
        return self._analyze(text, "ik_smart")

    def analyze_max_word(self, text):
        """最大分词，细粒度"""
        return self._analyze(text, "ik_max_word")

    def extract_keywords(self, tokens):
        keywords = [token for token in tokens if len(token) > 1]
        return list(set(keywords))